package basic.serializeDemo;

import java.io.*;

/**
 * @Description: TODO 使用Serializable的子类Externalizable 序列化和反序列化
 * @Author: wzj
 * @Date: 2021/2/23 9:35
 */
public class ExternalizeDemo {
    public static void main(String[] args) {
        try {
            serialize();
//            deserialize();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void serialize() throws IOException {
        //序列化
        ExternalizeObj externalizeObj=new ExternalizeObj("测试",20,"红色",10);
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("C:\\Users\\007\\Desktop\\testObj.txt"));
        objectOutputStream.writeObject(externalizeObj);
        objectOutputStream.close();
        System.out.println("序列化："+externalizeObj.toString());
    }
    public static void deserialize() throws IOException, ClassNotFoundException {
        //反序列化
        ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("C:\\Users\\007\\Desktop\\testObj.txt"));
        ExternalizeObj externalizeObj1=(ExternalizeObj) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println("反序列化："+externalizeObj1.toString());
    }
}

class ExternalizeObj implements Externalizable {

    private String name;
    private Integer price;
    private String color;
    private transient int length;//这里的transient不管用，writeExternal里面控制是否进行序列化，readExternal控制是否进行反序列化

    public ExternalizeObj() {
    }

    public ExternalizeObj(String name, Integer price, String color, int length) {
        this.name = name;
        this.price = price;
        this.color = color;
        this.length = length;
    }

    @Override
    public String toString() {
        return "{name: \"" + name + "\", price: \"" + price + "\", color: \"" + color + "\", length: \"" + length
                + "\"}";
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        System.out.println("[模拟日志记录]writeExternal.");

        out.writeUTF(name);
        out.writeInt(price);
//        out.writeUTF(color);//注释掉此行color将不能序列化
        out.writeInt(length);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        System.out.println("[模拟日志记录]readExternal.");

        name = in.readUTF();
        price = in.readInt();
//        color = in.readUTF();//注释掉此行color将不能反序列化
        length = in.readInt();
    }
}
